#pragma onece

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctemplate/template.h>

#include "oj_model_db.hpp"

namespace ns_view
{
    using std::string;
    using namespace ns_model;

    string template_path = "./template_html/";

    class View
    {
    public:
        View() {}
        ~View() {}
        bool AllRenderHTML(std::vector<Question> &questions, string *html)
        {
            // 对题目列表进行排序
            std::sort(questions.begin(), questions.end(), [](const Question &q1, const Question &q2)
                      { return std::stoi(q1.number) < std::stoi(q2.number); });
            // 源网页路径
            string src_html = template_path + "all_questions.html";
            // 构建字典
            ctemplate::TemplateDictionary root("all_questions");
            for (const auto &q : questions)
            {
                ctemplate::TemplateDictionary *sub_dict = root.AddSectionDictionary("question_list");
                sub_dict->SetValue("number", q.number);
                sub_dict->SetValue("title", q.title);
                sub_dict->SetValue("difficulty", q.difficulty);
            }
            // 获取源网页
            ctemplate::Template *tpl = ctemplate::Template::GetTemplate(src_html, ctemplate::DO_NOT_STRIP);
            if (tpl == nullptr)
            {
                LOG(FATAL) << "题库网页加载失败\n";
                return false;
            }
            // 渲染
            tpl->Expand(html, &root);
            return true;
        }
        bool OneRenderHTML(const Question &question, string *html)
        {
            // 源网页路径
            string src_html = template_path + "one_question.html";
            // 构建字典
            ctemplate::TemplateDictionary root("question");
            root.SetValue("number", question.number);
            root.SetValue("title", question.title);
            root.SetValue("difficulty", question.difficulty);
            root.SetValue("desc", question.desc);
            root.SetValue("code", question.header);
            // 获取源网页
            ctemplate::Template *tpl = ctemplate::Template::GetTemplate(src_html, ctemplate::DO_NOT_STRIP);
            if (tpl == nullptr)
            {
                LOG(FATAL) << "题目网页加载失败\n";
                return false;
            }
            // 渲染
            tpl->Expand(html, &root);
            return true;
        }
    };

}